﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace SSL_Server
{
    public partial class Form1 : Form
    {
        private WebServer _server;
        private const int DefaultPort = 443;
        private Dictionary<string, string> _certificatePaths = new Dictionary<string, string>();
        private Dictionary<string, string> _certificatePasswords = new Dictionary<string, string>();
        private Dictionary<string, string> _responses = new Dictionary<string, string>();
        
        public Form1()
        {
            InitializeComponent();
            // 初始化默认域名配置
            _certificatePaths["zyb.pub"] = "zyb.pub.pfx";
            _certificatePasswords["zyb.pub"] = "ja8phraa";
            _responses["zyb.pub"] = "<html><body>Hello from SSL WebServer!</body></html>";
        }
        private void Form1_Load_1(object sender, EventArgs e)
        {
            SOFT_VER.Text = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            try
            {
                if (File.Exists("config.json"))
                {
                    string json = File.ReadAllText("config.json");
                    var config = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);

                    _certificatePaths = config.CertificatePaths.ToObject<Dictionary<string, string>>();
                    _certificatePasswords = config.CertificatePasswords.ToObject<Dictionary<string, string>>();
                    _responses = config.Responses.ToObject<Dictionary<string, string>>();

                    txtLog.AppendText($"已加载{_certificatePaths.Count}个域名配置\r\n");
                    RefreshDomainList();
                }
            }
            catch (Exception ex)
            {
                txtLog.AppendText($"读取配置文件失败: {ex.Message}\r\n");
            }

            button1_Click(null, null);

        }

        // 添加新域名配置
        private void AddDomainConfig(string domain, string certPath, string password, string response)
        {
            _certificatePaths[domain] = certPath;
            _certificatePasswords[domain] = password;
            _responses[domain] = response;
            txtLog.AppendText($"已添加域名配置: {domain}\r\n");
        }
        
        // 删除域名配置
        private void RemoveDomainConfig(string domain)
        {
            _certificatePaths.Remove(domain);
            _certificatePasswords.Remove(domain);
            _responses.Remove(domain);
            txtLog.AppendText($"已移除域名配置: {domain}\r\n");
            RefreshDomainList();
        }
        
        private void RefreshDomainList()
        {
            lstDomains.Items.Clear();
            foreach(var domain in _certificatePaths.Keys)
            {
                lstDomains.Items.Add(domain);
            }
        }
        
      
        private void btnRemoveDomain_Click(object sender, EventArgs e)
        {
            if(lstDomains.SelectedItem != null)
            {
                string domain = lstDomains.SelectedItem.ToString();
                RemoveDomainConfig(domain);
            }
        }
        

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                _server = new WebServer(DefaultPort, _certificatePaths, _certificatePasswords, _responses);
                _server.Start();
                txtLog.AppendText($"服务器已启动，监听端口 {DefaultPort}\r\n");
                txtLog.AppendText($"已加载证书: {string.Join(", ", _certificatePaths.Keys)}\r\n");
            }
            catch (Exception ex)
            {
                txtLog.AppendText($"启动失败: {ex.Message}\r\n");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (_server != null)
            {
                _server.Stop();
                txtLog.AppendText("服务器已停止\r\n");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                // 保存配置为JSON格式
                var config = new {
                    CertificatePaths = _certificatePaths,
                    CertificatePasswords = _certificatePasswords,
                    Responses = _responses
                };
                
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(config,   Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText("config.json", json);
                txtLog.AppendText("配置保存成功\r\n");
            }
            catch (Exception ex)
            {
                txtLog.AppendText($"保存失败: {ex.Message}\r\n");
            }
        }

      
        /// <summary>
        /// AddDomain
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            using (var dialog = new DomainConfigDialog())
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    AddDomainConfig(dialog.DomainName, dialog.CertPath, dialog.CertPassword, dialog.ResponseContent);
                    RefreshDomainList();
                }
            }
        }
    }
}
